const {
  getStudentInformation,
  updateStudentInformation,
  getStudentList,
  getCoachStudentListById, newStudent, delStudent
} = require('../controller/student')
const {newAccount, deleteAccountByUsername} = require("../controller/user");
const {SuccessModel, ErrorModel} = require('../model/response')
var express = require('express');
var router = express.Router();

/**
 * 管理员路由操作
 * StudentUser.vue: /del/:id, /update, /new, list
 */
// 获取所有学员信息
router.get('/list', (req, res, next) => {
  const result = getStudentList()
  return result.then(rows => {
    res.json(new SuccessModel(rows))
  })
});
// 添加学员，创建默认账户
router.post('/new', async (req, res, next) => {
  const StudentResult = await newStudent(req.body.student)
  if (StudentResult) {
    const UserResult = await newAccount(req.body.account)
    if (UserResult) {
      res.json(new SuccessModel('添加学员成功'))
    }
  } else {
    res.json(new ErrorModel('添加学员失败'))
  }
})
// 修改学员
router.post('/update', (req, res, next) => {
  const result = updateStudentInformation(req.body)
  return result.then(val => {
    if (val) {
      res.json(new SuccessModel('修改学员信息成功'))
    } else {
      res.json(new ErrorModel('修改学员信息失败'))
    }
  })
})
// 删除学员，同时删除账户
router.post('/del/:id', async (req, res, next) => {
  const StudentResult = await delStudent(req.params.id)
  if (StudentResult) {
    const UserResult = await deleteAccountByUsername(req.body.identify)
    if (UserResult) {
      res.json(new SuccessModel('删除学员成功'))
    }
  } else {
    res.json(new ErrorModel('删除学员失败'))
  }
})
/**
 * 教练路由操作
 * CoachStudent.vue: /list/:id
 */
// 根据教练 id === coach_id 获取学员信息
router.post('/list/:id', (req, res, next) => {
  const result = getCoachStudentListById(req.params.id)
  return result.then(rows => {
    res.json(new SuccessModel(rows))
  })
});

/**
 * 学员路由操作
 * Personal.vue: /update, /detail
 * AppointTrain.vue: /detail
 */
// 获取学员详细信息
router.post('/detail', (req, res, next) => {
  const result = getStudentInformation(req.session.username)
  return result.then(row => {
    if (row.identify) {
      res.json(new SuccessModel(row))
    } else {
      res.json(new ErrorModel('获取学员信息失败'))
    }
  })
})

module.exports = router;
